package com.tt.utils.wordUtils.renderplicy;

import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.tt.utils.wordUtils.entity.LinkContent;
import com.tt.utils.wordUtils.utils.BaseWordUtiils;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import java.util.List;

/**
 * @Title: HyperlinkRenderPolicy
 * @Author zl
 * @Package com.oberyun.goHAZOP.utils.wordUtils.renderplicy
 * @Date 2025/9/17 16:05
 * @description: 超链接地址渲染策略
 */

/**
 * @Title: HyperlinkRenderPolicy
 * @Author zl
 * @Date 2025/9/17
 * @description: 超链接地址渲染策略
 */
public class HyperlinkRenderPolicy extends AbstractRenderPolicy<LinkContent> {

    @Override
    public void doRender(RenderContext<LinkContent> context) throws Exception {
        LinkContent data = context.getData();
        if (data == null || data.getLinkBody() == null || data.getLinkBody().isEmpty()) {
            return;
        }
        // 获取占位符所在的 run 和段落
        XWPFRun placeholderRun = context.getRun();
        XWPFParagraph paragraph = (XWPFParagraph) placeholderRun.getParent();

        // 删除占位符 run
        int pos = paragraph.getRuns().indexOf(placeholderRun);
        if (pos >= 0) {
            paragraph.removeRun(pos);
        }

        // 遍历生成超链接
        List<LinkContent.LinkBody> linkBodyList = data.getLinkBody();
        for (int i = 0; i < linkBodyList.size(); i++) {
            LinkContent.LinkBody item = linkBodyList.get(i);
            BaseWordUtiils.appendExternalHyperlink(item.getLinkUrl(), item.getTitle(), paragraph);
            // 多个超链接之间插入空格
            if (i < linkBodyList.size() - 1) {
                XWPFRun spaceRun = paragraph.createRun();
                spaceRun.setText("  ");
            }
        }
    }

}
